/**
 * 公共的根据出生年月计算年龄的方法
 *  @param birthday 格式必须为2020-08-08
 */
export function getAge(birthday: any) {
  const birArr = birthday.split("-");
  const birYear = parseInt(birArr[0]);
  const birMonth = parseInt(birArr[1]);
  const birDay = parseInt(birArr[2]);

  d = new Date();
  const nowYear = d.getFullYear();
  const nowMonth = d.getMonth() + 1; // 记得加1
  const nowDay = d.getDate();
  let returnAge;

  if (birArr == null) {
    return false;
  }
  var d = new Date(birYear, birMonth - 1, birDay);
  if (
    d.getFullYear() === birYear &&
    d.getMonth() + 1 === birMonth &&
    d.getDate() === birDay
  ) {
    if (nowYear === birYear) {
      returnAge = 0; //
    } else {
      const ageDiff = nowYear - birYear; //
      if (ageDiff > 0) {
        if (nowMonth === birMonth) {
          const dayDiff = nowDay - birDay; //
          if (dayDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        } else {
          const monthDiff = nowMonth - birMonth; //
          if (monthDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        }
      } else {
        // 返回-1 表示出生日期输入错误 晚于今天 '出生日期晚于今天，数据有误'
        return -1;
      }
    }
    return returnAge;
  }
}

// 状态翻译 data是当前状态数据列表 value要翻译的值
export function selectDictLabel(data: any, value: any) {
  const actions: any[] = [];
  Object.keys(data).map((key) => {
    if (data[key].value + "" === value) {
      actions.push(data[key].label);
      return false;
    }
  });
  return actions.join("");
}

// 把日期范围构造成beginTime和endTime
export function addDateRange(params: any, dateRange: any) {
  const search = params;
  search.beginTime = "";
  search.endTime = "";
  if (dateRange != null && dateRange !== "" && dateRange !== undefined) {
    search.beginTime = dateRange[0];
    search.endTime = dateRange[1];
  }
  return search;
}

/** *
 * 构造树的数据结构
 * @param data 要构造的数据源
 * @param id 字段ID  默认为id
 * @param parentId 父节点字端  默认为parentId
 * @param children 子节点的字段 默认为children
 * @param rootId 根节点的ID  默认为0
 */
export function handleTree(
  data: any,
  id: any,
  parentId?: any,
  children?: any,
  rootId?: any
) {
  id = id || "id";
  parentId = parentId || "parentId";
  children = children || "children";
  rootId = rootId || 0;
  // 对源数据进行深度克隆
  const cloneData = JSON.parse(JSON.stringify(data));
  // 循环所有的项目
  const treeData = cloneData.filter((father) => {
    const branchArr = cloneData.filter((child) => {
      return father[id] === child[parentId];
    });
    branchArr.length > 0 ? (father.children = branchArr) : "";
    // 返回上一层
    return father[parentId] === rootId;
  });
  return treeData !== "" ? treeData : data;
}
